
import { _decorator, Asset, SpriteAtlas, SpriteFrame, resources } from 'cc';
import * as cc from 'cc';
/**
 * 资源加载
 * @author 神兽白泽
 * @description 交流群：415468592
 */
export default class LoaderMgr {
    private static _profile_res = {};
    private static _bundle = null;
    public static setBundle(bundle) {
        bundle && (this._bundle = bundle);
    }
    public static getBundle() {
        return this._bundle || resources;
    }

    /**
     * 根据类型异步加载
     * @param relative_path 资源路径
     * @param asset_type 资源类型
     * @param complete_callback 加载回调
     * @returns 
     */
    public static loadAssetByType<T extends typeof Asset>(relative_path: string, asset_type: T, complete_callback?: Function): Promise<InstanceType<T>> {
        return new Promise((resolve: (data) => void, reject) => {
            this.getBundle().load(relative_path, asset_type, (error, asset) => {
                if (error) {
                    error('loadAssetByType failed ... and path = ' + relative_path, '==error:', JSON.stringify(error));
                    reject();
                    return;
                } else {
                    complete_callback && complete_callback(asset);
                    resolve(asset);
                }
            });
        });
    }
    // Promise用法：
    //    async start() {
    //        // 动态加载应用Promise示例：
    //        let path = 'test_prefab';
    //        let asset = await mk.loader.loadAssetByType(path, cc.Prefab)
    //        this.test_prefab = asset;
    //        let node = cc.instantiate(asset);
    //        node.parent = this.node;
    //        this.test_node = node;
    //        cc.log(asset)
    //    }
    /** 获取图片纹理 by 图集
    * - sprite_frame_name：要获取的纹理名字
    * - arr_atlas：图集列表
    */
    public static getSpriteFrameByArrAlst(sprite_frame_name: string, arr_atlas: Array<cc.SpriteAtlas>): SpriteFrame {
        let count = arr_atlas.length;
        for (let i = 0; i < count; i++) {
            let _atlas = arr_atlas[i];
            let spf = _atlas.getSpriteFrame(sprite_frame_name);
            if (spf) return spf;
        }
        return null;
    }
}